
import React, { PureComponent } from 'react'

import { Select, Radio, Form, Input, Row, Col, Button, Cascader, DatePicker } from 'antd';
import { connect } from 'react-redux'
import { getAreaJson } from "@sagas/common";
import ImageUpload from "@common/presentational/ImageUpload";
const FormItem = Form.Item;
import dayjs from 'dayjs';
import PageBackHeader from "@common/PageBackHeader";
import { withRouter } from 'react-router-dom'
import { wechatPayApply } from "@sagas/payment";
import { getHistoryMatchParams } from "@utils/setUrlQuery";
import { uploadWechatImage } from '@utils/qiniu'
import {
    getWechatMiniInfo
} from "@sagas/thirdparty";

const getReformedData = (data) => {
    const _data = {
        ...data
    }
    return {
        ..._data,
    }
}

const initialValue = {
    name: '',
}
function mapStateToProps(state) {
    const { common } = state
    return {
        cascaderList: common.cascaderList || []
    }
}
@connect(
    mapStateToProps
    , {
        getAreaJson,
        wechatPayApply,
        getWechatMiniInfo
    })
@withRouter
class PaymentWechatCreate extends PureComponent {

    constructor(props) {
        super(props);
        const { location } = props
        const { type, id } = getHistoryMatchParams(props)
        const { state } = location
        this.state = {
            type,
            id,
            store_name:'',
            store_qr_code:'',
            formData: id ? {
                ...initialValue,
                ...getReformedData(state),
            } : {
                ...initialValue
            }
        }
        this.formRef = React.createRef()

        this.handleSubmit = this.handleSubmit.bind(this)
        this.submitForm = this.submitForm.bind(this)
        this.cancelFunc = this.cancelFunc.bind(this)
    }

    componentDidMount() {
        this.props.getAreaJson()
        const { getWechatMiniInfo } = this.props
        getWechatMiniInfo((res) => {
            // 已创建
            if(!res.version?.release_version){
                this.setState({
                    store_name:res.name,
                    store_qr_code: res.qr_code_url
                })
            }
        }, () => {
            
        })
    }

    async handleSubmit(values) {
        const { id, type, store_name, store_qr_code } = this.state
        let params = {
            type: type,
            "merchant_shortname": values.merchant_shortname,
            "id_doc_type": "IDENTIFICATION_TYPE_MAINLAND_IDCARD",
            "id_card_info": {
                "id_card_copy": await uploadWechatImage(values.id_card_copy),
                "id_card_national": await uploadWechatImage(values.id_card_national),
                "id_card_name": values.id_card_name,
                "id_card_number": values.id_card_number,
                "id_card_valid_time": values.times === '2' ? '长期' : dayjs(values.date_limitation).format('YYYY-MM-DD'),
            },
            "need_account_info": true,
            "account_info": {
                "bank_account_type": values.bank_account_type,
                "account_bank": values.account_bank,
                "account_name": values.account_name,
                "bank_address_code": values.bank_address_code[values.bank_address_code.length - 1],
                "account_number": values.account_number
            },
            "contact_info": {
                "contact_type": "65",
                "contact_name": values.contact_name,
                "contact_id_card_number": values.contact_id_card_number,
                "mobile_phone": values.mobile_phone,
                "contact_email": values.contact_email
            }
        }
        if(values.qualifications && values.qualifications.length){
            let imgArr = []
            values.qualifications.map(async item=>{
                imgArr.push(await uploadWechatImage(item))
            })
            params.qualifications = imgArr
        }
        if (type === 3) {
            params.organization_cert_info = {
                "organization_copy": await uploadWechatImage(values.organization_copy),
                "organization_number": values.organization_number,
                "organization_time": values.organization_times === '2' ? '长期' : dayjs(values.organization_time).format('YYYY-MM-DD'),
            }
        }
        if (type === 2) {
            params.biz_license_info = {
                "business_license_copy": await uploadWechatImage(values.business_license_copy),
                "business_license_number": values.business_license_number,
                "merchant_name": values.merchant_name,
                "legal_person": values.legal_person,
            }
        }
        params.sales_scene_info = {
            "store_name": store_name,
            "store_qr_code": store_qr_code,
        }
        if (id) {
            params.id = id
        }
        this.props.wechatPayApply({
            ...params,
        }, () => {
            this.cancelFunc()
        })
    }

    submitForm() {
        this.formRef.current?.submit()
    }

    filter(inputValue, path) {
        return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }

    cancelFunc() {
        this.props.goBack ? this.props.goBack('/payment/wechat') : this.props.history.goBack('/payment/wechat')
    }

    render() {
        const { formData, id, type } = this.state
        const { cascaderList } = this.props
        const isEdit = !!id
        return (
            <div className="bilin-web">
                <PageBackHeader title={isEdit ? '编辑收款账号' : '新建收款账号'} />
                <div className="bilin-web-body form-page with-footer">
                    <Form
                        ref={this.formRef}
                        name="payment-edit"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        initialValues={formData}
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                        onFinish={this.handleSubmit}
                    >
                        <div className="ft-16 pdt-36 pdb-36">商户信息</div>
                        <FormItem
                            label="商户简称: "
                            name='merchant_shortname'
                            extra='此信息将在支付完成页向客户展示'
                            rules={[
                                { required: true, message: '请输入名称', },
                            ]}
                        >
                            <Input placeholder="请输入名称" />
                        </FormItem>
                        {type === 2 ? <>
                            <Form.Item
                                label='营业执照'
                                name='business_license_copy'
                                rules={[
                                    {
                                        required: true,
                                        message: '请上传营业执照'
                                    },
                                ]}
                            >
                                <ImageUpload
                                    accept='image/png, image/jpeg, image/jpg'
                                    maxFileSize="2m"
                                    uploadIntro={(
                                        <div className="ft-12 ft-clr-ml mgl-16" style={{ width: '340px' }}>
                                            请上传证件的彩色扫描件或拍摄照片，黑白复印件需加盖公章；<br />
                                            保证图片信息完整清晰，不得添加无关水印，不接受二次处理
                                        </div>
                                    )}
                                />
                            </Form.Item>
                            <FormItem
                                label="证件注册号: "
                                name='business_license_number'
                                rules={[
                                    { required: true, message: '请输入证件注册号', },
                                ]}
                            >
                                <Input placeholder="请输入证件注册号" />
                            </FormItem>
                            <FormItem
                                label="商户名称	: "
                                name='merchant_name'
                                rules={[
                                    { required: true, message: '请输入商户名称', },
                                ]}
                            >
                                <Input placeholder="请输入商户名称" />
                            </FormItem>
                            <FormItem
                                label="经营者: "
                                name='legal_person'
                                rules={[
                                    { required: true, message: '请输入经营者/法定代表人姓名', },
                                ]}
                            >
                                <Input placeholder="请输入经营者/法定代表人姓名" />
                            </FormItem>
                        </> : null}
                        {type === 3 ? <>
                            <Form.Item
                                label='组织机构代码证'
                                name='organization_copy'
                                rules={[
                                    {
                                        required: true,
                                        message: '请上传组织机构代码证'
                                    },
                                ]}
                            >
                                <ImageUpload
                                    accept='image/png, image/jpeg, image/jpg'
                                    maxFileSize="2m"
                                    uploadIntro={null}
                                />
                            </Form.Item>
                            <FormItem
                                label="组织机构代码: "
                                name='organization_number'
                                rules={[
                                    { required: true, message: '请输入组织机构代码', },
                                ]}
                            >
                                <Input placeholder="请输入组织机构代码" />
                            </FormItem>
                            <FormItem
                                label="有效期: "
                                name='organization_times'
                                rules={[
                                    { required: true, message: '请选择有效期', },
                                ]}
                            >
                                <Radio.Group >
                                    <Radio value='1'>非长期</Radio>
                                    <Radio value='2'>长期</Radio>
                                </Radio.Group>
                            </FormItem>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) => prevValues.organization_times !== currentValues.organization_times}
                            >
                                {({ getFieldValue }) => {
                                    return getFieldValue('organization_time') === '1' ? (<>
                                        <Row>
                                            <Col span={4} />
                                            <Col span={20}>
                                                <FormItem
                                                    name='organization_time'
                                                    rules={[
                                                        { required: true, message: '请选择有效期', },
                                                    ]}
                                                >
                                                    <DatePicker />
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </>
                                    ) : null
                                }}
                            </Form.Item>
                            <Form.Item
                                label='特殊资质'
                                name='qualifications'
                            >
                                <ImageUpload
                                    accept='image/png, image/jpeg, image/jpg'
                                    maxFileSize="2m"
                                    maxLength={5}
                                    uploadIntro={(
                                        <div className="ft-12 ft-clr-ml mgl-16" style={{ width: '340px' }}>
                                            请根据商户经营业务要求是否需要提供相关资质（最多5张）<br />
                                            <a target='_blank' href="https://kf.qq.com/faq/190610B7baQb190610NN3mQN.html" >查看特殊资质</a>
                                        </div>
                                    )}
                                />
                            </Form.Item>
                        </> : null}
                        <div className="ft-16 pdt-36 pdb-36">经营者信息</div>
                        <Form.Item
                            label='身份证人像面'
                            name='id_card_copy'
                            rules={[
                                {
                                    required: true,
                                    message: '请上传身份证人像面'
                                },
                            ]}
                        >
                            <ImageUpload
                                accept='image/png, image/jpeg, image/jpg'
                                maxFileSize="2m"
                                uploadIntro={null}
                            />
                        </Form.Item>
                        <Form.Item
                            label='身份证国徽面'
                            name='id_card_national'
                            rules={[
                                {
                                    required: true,
                                    message: '请上传身份证国徽面'
                                },
                            ]}
                        >
                            <ImageUpload
                                accept='image/png, image/jpeg, image/jpg'
                                maxFileSize="2m"
                                uploadIntro={null}
                            />
                        </Form.Item>
                        <FormItem
                            label="身份证姓名: "
                            name='id_card_name'
                            rules={[
                                { required: true, message: '请输入身份证姓名', },
                            ]}
                        >
                            <Input placeholder="请输入身份证姓名" />
                        </FormItem>
                        <FormItem
                            label="身份证号码: "
                            name='id_card_number'
                            rules={[
                                { required: true, message: '请输入身份证号码', },
                            ]}
                        >
                            <Input placeholder="请输入身份证号码" />
                        </FormItem>
                        <FormItem
                            label="有效期: "
                            name='times'
                            rules={[
                                { required: true, message: '请选择有效期', },
                            ]}
                        >
                            <Radio.Group >
                                <Radio value='1'>非长期</Radio>
                                <Radio value='2'>长期</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.times !== currentValues.times}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('times') === '1' ? (<>
                                    <Row>
                                        <Col span={4} />
                                        <Col span={20}>
                                            <FormItem
                                                name='date_limitation'
                                                rules={[
                                                    { required: true, message: '请选择有效期', },
                                                ]}
                                            >
                                                <DatePicker />
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                        <div className="ft-16 pdt-36 pdb-36">超级管理员</div>
                        <FormItem
                            label="姓名: "
                            name='contact_name'
                            rules={[
                                { required: true, message: '请输入姓名', },
                            ]}
                        >
                            <Input placeholder="请输入姓名" />
                        </FormItem>
                        <FormItem
                            label="手机号: "
                            name='mobile_phone'
                            rules={[
                                { required: true, message: '请输入手机号', },
                            ]}
                        >
                            <Input placeholder="请输入手机号" maxLength={11} />
                        </FormItem>
                        <FormItem
                            label="身份证号码: "
                            name='contact_id_card_number'
                            rules={[
                                { required: true, message: '请输入身份证号码', },
                            ]}
                        >
                            <Input placeholder="请输入身份证号码" />
                        </FormItem>
                        <FormItem
                            label="邮箱: "
                            name='contact_email'
                            rules={[
                                { required: true, message: '请输入邮箱', },
                            ]}
                        >
                            <Input placeholder="请输入邮箱" />
                        </FormItem>
                        <div className="ft-16 pdt-36 pdb-36">结算账户</div>
                        <FormItem
                            label="账户类型: "
                            name='bank_account_type'
                            rules={[
                                { required: true, message: '请选择账户类型', },
                            ]}
                        >
                            <Radio.Group >
                                {type !== 1 && <Radio value='74'>对公银行账户</Radio>}
                                {type !== 3 && <Radio value='75'>个人银行卡</Radio>}
                            </Radio.Group>
                        </FormItem>
                        <FormItem
                            label="开户名称: "
                            name='account_name'
                            rules={[
                                { required: true, message: '请输入开户名称', },
                            ]}
                        >
                            <Input placeholder="请输入开户名称" />
                        </FormItem>
                        <Form.Item
                            label='开户银行地址'
                            name='bank_address_code'
                            rules={[
                                { required: true, message: '请输入/选择服务区域', },
                            ]}
                        >
                            <Cascader
                                options={cascaderList}
                                placeholder="请输入/选择开户银行地址"
                                showSearch={{ filter: this.filter }}
                                changeOnSelect
                            />
                        </Form.Item>
                        <FormItem
                            label="开户行: "
                            name='account_bank'
                            rules={[
                                { required: true, message: '请选择开户行', },
                            ]}
                        >
                            <Select placeholder="请选择开户行" style={{ display: 'inline-block' }}>
                                <Select.Option value='中国银行'>中国银行</Select.Option>
                                <Select.Option value='建设银行'>建设银行</Select.Option>
                                <Select.Option value='工商银行'>工商银行</Select.Option>
                                <Select.Option value='农业银行'>农业银行</Select.Option>
                                <Select.Option value='招商银行'>招商银行</Select.Option>
                                <Select.Option value='邮政储蓄银行'>邮政储蓄银行</Select.Option>
                                <Select.Option value='交通银行'>交通银行</Select.Option>
                                <Select.Option value='浦发银行'>浦发银行</Select.Option>
                                <Select.Option value='广发银行'>广发银行</Select.Option>
                                <Select.Option value='民生银行'>民生银行</Select.Option>
                                <Select.Option value='平安银行'>平安银行</Select.Option>
                                <Select.Option value='中信银行'>中信银行</Select.Option>
                            </Select>
                        </FormItem>
                        <FormItem
                            label="银行账号: "
                            name='account_number'
                            rules={[
                                { required: true, message: '请输入银行账号', },
                            ]}
                        >
                            <Input placeholder="请输入银行账号" />
                        </FormItem>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button type="primary" ghost onClick={this.cancelFunc}>取消</Button>
                    <Button type="primary" onClick={this.submitForm}>{isEdit ? '确定修改' : '保存'}</Button>
                </div>
            </div>

        )
    }
}

export default PaymentWechatCreate